import React from 'react';
import { Modal, Button, Table, Tag, message } from 'antd';
import { CopyOutlined, DownloadOutlined } from '@ant-design/icons';
import { Coupon } from '@/types/coupon';

interface CouponResultModalProps {
  visible: boolean;
  onClose: () => void;
  onCreateAnother: () => void;
  generatedCoupons: Coupon[];
  couponInfo: {
    name: string;
    type: string;
    value: string;
    threshold: string;
    expireAt: string;
    startDate: string;
    endDate: string;
    isDiscount?: boolean;
  };
}

const CouponResultModal: React.FC<CouponResultModalProps> = ({
  visible,
  onClose,
  onCreateAnother,
  generatedCoupons,
  couponInfo
}) => {
  // 复制单个优惠码
  const handleCopyCode = (code: string) => {
    navigator.clipboard.writeText(code).then(() => {
      message.success('复制成功');
    }).catch(() => {
      message.error('复制失败');
    });
  };

  // 导出CSV
  const handleExportCSV = () => {
    if (generatedCoupons.length === 0) {
      message.warning('没有数据可导出');
      return;
    }

    let csvContent = "序号,优惠码,生成时间,优惠类型,使用门槛,有效期\n";
    
    generatedCoupons.forEach((coupon, index) => {
      csvContent += `${index + 1},${coupon.code},${coupon.createTime},${couponInfo.type},${couponInfo.threshold},${coupon.expiry}\n`;
    });
    
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.setAttribute("href", url);
    link.setAttribute("download", `${couponInfo.name}_优惠码列表_${new Date().toISOString().split('T')[0]}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  // 表格列定义
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      render: (_: any, __: any, index: number) => index + 1,
      width: 60
    },
    {
      title: '优惠码',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (record: Coupon) => (
        <Button
          icon={<CopyOutlined />}
          size="small"
          onClick={() => handleCopyCode(record.code)}
        >
          复制
        </Button>
      ),
    },
  ];

  return (
    <Modal
      title="优惠券生成结果"
      open={visible}
      onCancel={onClose}
      footer={null}
      width={700}
      className="coupon-result-modal"
    >
      <div className="mb-4">
        <div className="flex items-center justify-between mb-2">
          <h3 className="text-lg font-semibold">{couponInfo.name}</h3>
          <Tag color="success">生成成功</Tag>
        </div>
        <p className="text-sm text-gray-600 mb-4">优惠券已生成完毕，请复制或导出以下优惠码列表提供给用户兑换使用。</p>
        
        <div className="flex justify-between items-center mb-2">
          <div className="font-semibold">优惠码列表 (<span>{generatedCoupons.length}</span>个)</div>
          <Button 
            type="primary" 
            icon={<DownloadOutlined />} 
            onClick={handleExportCSV}
          >
            导出CSV
          </Button>
        </div>
        
        <div className="bg-gray-50 border border-gray-200 rounded-lg p-2" style={{ maxHeight: '300px', overflowY: 'auto' }}>
          <Table 
            dataSource={generatedCoupons} 
            columns={columns} 
            rowKey="code"
            pagination={false}
            size="small"
          />
        </div>
        
        <div className="text-sm text-gray-500 mt-2">
          提示：点击优惠码右侧的复制按钮可快速复制单个优惠码，或使用导出CSV下载完整列表。
        </div>
      </div>
      
      <div className="grid grid-cols-2 gap-4 mb-4">
        <div>
          <div className="form-group">
            <label className="form-label">优惠类型</label>
            <div>
              <span className={`coupon-type-badge ${couponInfo.isDiscount ? 'discount-type' : 'fixed-type'}`}>
                {couponInfo.type}
              </span>
            </div>
          </div>
        </div>
        <div>
          <div className="form-group">
            <label className="form-label">使用门槛</label>
            <div>{couponInfo.threshold}</div>
          </div>
        </div>
      </div>
      
      <div className="grid grid-cols-2 gap-4 mb-4">
        <div>
          <div className="form-group">
            <label className="form-label">生效日期</label>
            <div>{couponInfo.startDate}</div>
          </div>
        </div>
        <div>
          <div className="form-group">
            <label className="form-label">过期日期</label>
            <div>{couponInfo.endDate}</div>
          </div>
        </div>
      </div>
      
      <div className="flex justify-end gap-2">
        <Button onClick={onClose}>返回列表</Button>
        <Button type="primary" onClick={onCreateAnother}>创建新优惠券</Button>
      </div>
    </Modal>
  );
};

export default CouponResultModal; 